package com.cqs.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:li
 * <p>
 * create date: 18-5-30 15:13
 */
public class RemoveNthNodeFromEndofList19 {


    /**
     * 利用两个指针
     * p 已经 fastp 其中fastp和p之间相隔n-1
     *
     * @param head
     * @param n
     * @return
     */
    //16ms
    public ListNode removeNthFromEnd(final ListNode head, int n) {
        ListNode p = head, fastp = head, pcur = null;
        //p和fastp相隔n-1
        for (int i = 1; i < n; i++) {
            fastp = fastp.next;
        }
        while (fastp.next != null) {
            fastp = fastp.next;
            pcur = p;
            p = p.next;
        }
        if (pcur == null) {
            return head.next;
        }
        pcur.next = p.next;
        return head;
    }


    //30 ms
    // 空间 和 时间复杂度较高
    public ListNode removeNthFromEnd2(final ListNode head, int n) {
        List<ListNode> list = new ArrayList<>();
        ListNode tmp = head;
        while (tmp != null) {
            list.add(tmp);
            tmp = tmp.next;
        }
        int len = list.size();
        if (len == n) return head.next;
        ListNode pre = list.get(len - n - 1);
        ListNode cur = list.get(len - n);
        pre.next = cur.next;
        return head;
    }
}
